package zhongbo.java.websocket.demo.web.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhongbo.java.websocket.demo.model.History;
import zhongbo.java.websocket.demo.model.User;
import zhongbo.java.websocket.demo.service.*;
import zhongbo.java.websocket.demo.util.SpringContextHolder;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年03月17日 星期一 21:47:58
 */
@ServerEndpoint(value = "/chat/{userId}")
@Component
@Slf4j
public class ChatWebSocket {

    public static Map<String, Session> sessionMap = new HashMap<>();

    @PostConstruct
    public void init() {
        log.info("启动Websocket");
    }

    private static IOnlineUserService onlineUserService;
    private static IUserService userService;
    private static IMessageRankService messageRankService;
    private static MessagePubSub messagePubSub;

    @Autowired
    public void setServices(
            IOnlineUserService ous,
            IMessageRankService mrs,
            IUserService us,
            MessagePubSub mps
    ) {
        onlineUserService = ous;
        messageRankService = mrs;
        userService = us;
        messagePubSub = mps;
    }

    /*
    建立连接
     */
    @OnOpen
    public void openConn(Session session, @PathParam("userId") String userId) throws IOException {
        String sessionId = session.getId();
        log.info("建立ws连接: {}", sessionId);
        sendMessage(session, "hello");
        if (StrUtil.isBlank(userId)) {
            doClose(session, "未识别用户id,拒绝登录");
            return;
        }
        User one = userService.findOne(userId);
        if (one == null) {
            doClose(session, "用户id不存在,拒绝登录");
            return;
        }
        // 用户登录,记录在线人数
        onlineUserService.userLogin(userId);
        sessionMap.put(sessionId, session);
    }

    private void doClose(Session session, String msg) {
        try {
            if (StrUtil.isNotBlank(msg)) {
                sendMessage(session, "错误:" + msg);
            }
            session.close();
        } catch (IOException e) {
            log.error("断开连接异常: {}", e.getMessage());
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason, @PathParam("userId") String userId) {
        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        log.info("关闭ws连接: {}, reason: {}", sessionId, reasonPhrase);
        // 用户退出了
        if (StrUtil.isNotBlank(userId)) {
            onlineUserService.userLogout(userId);
        }
        sessionMap.remove(sessionId);
    }

    @OnMessage
    public void onMessage(Session session, String msg, boolean last, @PathParam("userId") String userId) {
        if (session.isOpen()) {
            log.info("收到ws消息 = " + msg);
            try {
                JSONObject jsonObject = JSONUtil.parseObj(msg);
                History history = jsonObject.toBean(History.class);
                getHistoryService().addHistory(history);
            } catch (Exception ignored) {
            }
            // 记录用户消息数
            if (messageRankService.checkRateLimit(userId)) {
                messageRankService.incrementMessageCount(userId);
            }
            // 给所有ws客户端广播消息
            // 通过redis广播后, 不必再直接广播消息
            // for (Session otherSession : sessionMap.values()) {
            //     sendMessage(otherSession, msg);
            // }
            // 广播
            messagePubSub.pubMessage(msg);
        }
    }

    private IHistoryService getHistoryService() {
        return SpringContextHolder.getBean(IHistoryService.class);
    }

    /**
     * 发送文本消息
     *
     * @param session ws会话对象
     * @param msg     消息文本
     */
    private void sendMessage(Session session, String msg) {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            log.error("给 ws 客户端: {} 发送消息失败", session.getId(), e);
        }
    }
}
